package com.itheima.tanhua.dubbo.mongo.api.impl;

import com.itheima.tanhua.api.AcousticApi;
import com.itheima.tanhua.mongo.Acoustic;
import com.itheima.tanhua.utils.UserHolder;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.util.List;

@DubboService
public class AcousticApiImpl implements AcousticApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //随机获得一条语音
    public List<Acoustic> findAcousticRandom(Long userId,Integer count){
        TypedAggregation aggregation =
                Aggregation.newAggregation(Acoustic.class,
                        Aggregation.match(Criteria.where("userId").ne(userId).and("pickup").is(false)),
                        Aggregation.sample(count));//随机获取count条动态
        AggregationResults<Acoustic> aggregate = mongoTemplate.aggregate(aggregation, Acoustic.class);
        //返回数据
        return aggregate.getMappedResults();
    }

    //更新语音是否被拾取
    public void updateById(Acoustic acoustic){
        //构建查询条件
        Query up = Query.query(Criteria.where("id").is(acoustic.getId()));
        Update update = new Update();
        update.set("pickup", acoustic.isPickup());
        update.set("pickupDateTime",acoustic.getPickupDateTime());
        update.set("pickupUserId", acoustic.getPickupUserId());
        //修改
        mongoTemplate.updateFirst(up, update, Acoustic.class);
    }

    //保存语音
    public void saveSound(Acoustic acoustic) {
        mongoTemplate.save(acoustic);
    }
}
